class MatriculasController < ApplicationController

  before_filter :login_required
  require_role 'marketing', :only=>[:destroy]
  
  def index
    store_location
    list
    render :action => 'list'
  end

  # GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html)
  verify :method => :post, :only => [ :destroy, :create, :update ],
         :redirect_to => { :action => :list }

  def list
    store_location
    @matricula_pages, @matriculas = paginate :matriculas, :per_page => 15, :order=>'fecha DESC'
    
    @page, @lnk_from, @lnk_to = numeros_pagina @matricula_pages
  end

  def show
    @matricula = Matricula.find(params[:id])
  end

  def new
    error = false
    flash[:error] = ''
    
    @matricula = Matricula.new
    @matricula.fecha = Date.today()
    
    if params[:visita_id] != nil then
      @matricula.visita = Visita.find(params[:visita_id])
      @matricula.instructor = @matricula.visita.instructor
    else
      flash[:error] += "Falta especificar una vista.<br/>"
      error = true
    end
    
    # preseteo el alumno segun lo que llego por params
    if params[:matricula_alumno] != nil then
      @matricula.persona_id = params[:matricula_alumno]
    else
      flash[:error] += "Falta especificar un alumno.<br/>"
      error = true
    end
    
    if error then
      redirect_back_or_default :action=>'list', :controller=>'matriculas'
    else
      flash[:error] = nil
    end
  end

  def create
    # TODO generar la ficha medica
    @matricula = Matricula.new(params[:matricula])
    if @matricula.save
      
      flash[:success] = "Matricula creada"
      
      # al crear la matricula me deja en la pagina del alumno para poder crearle el plan
      redirect_to :action => 'show', :controller=>'alumnos', :id => @matricula.persona
    else
      render :action => 'new'
    end
  end

  def edit
    @matricula = Matricula.find(params[:id])
  end

  def update
    @matricula = Matricula.find(params[:id])
    if @matricula.update_attributes(params[:matricula])
      flash[:success] = 'Matricula modificada.'
      redirect_back_or_default :action => 'show', :id => @matricula
    else
      render :action => 'edit'
    end
  end

  def destroy
    mat = Matricula.find(params[:id])
    mat.destroy
    redirect_back_or_default :action => 'list'
  end

  def live_search
    paginar_personas "coeficiente_id<>#{Coeficiente::ALUMNO}"
    render :partial=>'hits', :locals=>{:nombres=>params[:nombres],:apellidos=>params[:apellidos],:mail=>params[:mail],:profesion=>params[:profesion]}
  end
  
end 